package org.jms.examples.activemqexamples.pubsub;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;

public class Publisher {
	private TopicConnectionFactory factory = null;
	private TopicConnection connection = null;
	private TopicSession session = null;
	private TopicPublisher publisher = null;

	public void sendMessage() {
		try {
			factory = new ActiveMQConnectionFactory(
					ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
			ActiveMQTopic topic = new ActiveMQTopic("topic1");
			connection = factory.createTopicConnection();
			session = connection.createTopicSession(false,
					TopicSession.AUTO_ACKNOWLEDGE);
			publisher = session.createPublisher(topic);
			EventMessage eventMessage = new EventMessage(1,
					"Message from FirstClient");
			ObjectMessage objectMessage = session.createObjectMessage();
			objectMessage.setObject(eventMessage);
			connection.start();
			publisher.publish(objectMessage);
			System.out.println(this.getClass().getName()
					+ " has sent a message : " + eventMessage);
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		Publisher publisher = new Publisher();
		publisher.sendMessage();
	}

}
